import re

from logger import logger
from sub_events.base_event import BaseEvent, CHECK_RESULT_FAIL, CHECK_RESULT_PASS

LOGGER = logger.CustomLogger()


class CheckCommitMsg(BaseEvent):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.event_name_zh: str = "提交信息检查"
        self.event_name_en: str = "Commit Message Check"

        self.xts_tdd_expect_result = ["pass", "fail", "不涉及"]
        self.compatibility_expect_result = ["是", "否", "不涉及"]
        self.review_comments_result = ["是", "否", "yes", "no"]
        self.blacklist_words = {
            "华为用词": r"强基|黄区|蓝区|DTS|鸿蒙|EMUI|华为|合作|单(?:框架|框)|双(?:框架|框)|工号",
            "AR/IR/SR编号": r"(?:IR|AR|SR)\d{14}",
            "工号": r"\b(?:[a-z]\d{8}|\d{8}|[a-z]\d{6}|\d{6}|[a-z]wx\d{7}|wx\d{7})\b",
        }

        self.format_check = False
        self.word_check = False

    def parse_validation_results(self, text):
        """
        检查信息填充是否符合规范
        """

        def get_result(line: str, expect_result):
            split_key = ":"
            if "：" in line:
                split_key = "："
            tmp = line.split(split_key)
            if len(tmp) != 2:
                return False
            result = tmp[1].strip()
            return result.lower() in expect_result

        tdd_result = False
        xts_result = False
        compatibility_result = False
        review_comment_result = False
        lines = text.split("\r\n")
        for line in lines:
            if "TDD自验结果(如有失败用例需提供基线执行情况)" in line:
                tdd_result = get_result(line, self.xts_tdd_expect_result)
            if "XTS自验结果(如有失败用例需提供基线执行情况)" in line:
                xts_result = get_result(line, self.xts_tdd_expect_result)
            if "是否涉及非兼容变更" in line:
                compatibility_result = get_result(line, self.compatibility_expect_result)
            if "检视意见是否都已闭环" in line:
                review_comment_result = get_result(line, self.review_comments_result)

        return tdd_result and xts_result and compatibility_result and review_comment_result

    def check_text_for_patterns(self, text):
        """
        检查文本中是否包含匹配指定模式的字符串
        返回包含匹配结果的字典
        """
        results = {}

        for pattern_name, pattern in self.blacklist_words.items():
            # 使用IGNORECASE标志使匹配不区分大小写
            matches = re.findall(pattern, text, re.IGNORECASE)
            if matches:
                results[pattern_name] = matches

        return results

    def execute(self):
        """
        检查提交信息是否合规
        """
        commit_msg = self.hook.pull_request.get("body")
        match_result = ""
        if not commit_msg:
            self.failed = True
        else:
            self.format_check = self.parse_validation_results(commit_msg)
            matches = self.check_text_for_patterns(commit_msg)
            if matches:
                self.word_check = False
                match_result = "在提交信息中发现了以下匹配：\n"

                for pattern_type, found_matches in matches.items():
                    match_result += f"\n{pattern_type} 匹配项 ({len(found_matches)}个):"
                    for i, match in enumerate(found_matches, 1):
                        match_result += f"\n  · {match}"
            else:
                self.word_check = True
            self.failed = not (self.format_check and self.word_check)
        if not self.format_check:
            suggestion = """请检查提交信息中的：

    是否涉及非兼容变更: 是否携带并仅保留(是/否)中的一个选项（不包含括号）。
    TDD自验结果(如有失败用例需提供基线执行情况): 是否携带并仅保留(Pass/Fail/不涉及)中的一个选项（不包含括号）。
    XTS自验结果(如有失败用例需提供基线执行情况): 是否携带并仅保留(Pass/Fail/不涉及)中的一个选项（不包含括号）。
    检视意见是否都已闭环(无检视意见填是)：是否携带并仅保留(是/否)中的一个选项（不包含括号）。


Please check in the commit message:

    是否涉及非兼容变更: ensure it is correctly filled with one of the options: (是/否).
    TDD自验结果(如有失败用例需提供基线执行情况): ensure it is correctly filled with one of the options: (Pass/Fail/不涉及).
    XTS自验结果(如有失败用例需提供基线执行情况): ensure it is correctly filled with one of the options: (Pass/Fail/不涉及).
    检视意见是否都已闭环(无检视意见填是)：ensure it is correctly filled with one of the options: (是/否).
"""
            self.comment = suggestion
        elif not self.word_check:
            LOGGER.error(f"{self.hook.pr_number}] 用语不规范：{match_result}")
            self.comment = "请注意检查提交信息中的规范用语，如有疑问请联系 @sunfei2021"
